﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Chapter26.TcpSendWithReceive
{
    /// <summary>
    /// TcpReceive.xaml 的交互逻辑
    /// </summary>
    public partial class TcpReceiveWindow : Window
    {
        public TcpReceiveWindow()
        {
            InitializeComponent();
            Task.Run(new Action(Listen));
        }

        private void Listen()
        {
            while (true)
            {
                var localAddress = IPAddress.Parse("127.0.0.1");
                var port = 2112;
                var tcpListener = new TcpListener(localAddress, port);
                tcpListener.Start();
                var tcpClient = tcpListener.AcceptTcpClient();
                var networkStream = tcpClient.GetStream();
                var streamReader = new StreamReader(networkStream);
                var result = streamReader.ReadToEnd();
                Dispatcher.Invoke(new Action<string>(UpdateTextBox), new object[] { result });
                tcpListener.Stop();
            }
        }

        private void UpdateTextBox(string text)
        {
            receiveTextBox.Text = text;
        }
    }
}
